package com.xinzhidi.common.utils;

import com.xinzhidi.common.utils.http.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


/**
 * 天气工具类
 */
public class WeatherUtil {

    public static String getWeatherInfo(String areaCode, String previewType, String key) {
        try {
            // 高德天气url
            String urlPrefix = "https://restapi.amap.com/v3/weather/weatherInfo?";
            // 请求参数（需排序
            String param = "city="+areaCode+"&key="+key+previewType;
            // md5加密得到签名(参数和秘钥）
            //String md5 = Md5Utils.getMD5(param+sig);

            URL url = new URL(urlPrefix+param);
            HttpURLConnection conn = UrlUtil.getConn(url);
            conn.setRequestMethod("GET");
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuilder result = null;
            while ((line = br.readLine())!= null){
                return line;
            }
            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getWeather(String cityId, String token, String path) {
        String host = "https://aliv18.data.moji.com";
        String method = "POST";
        String appcode = "099be5b5cc004417940942822525076d";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("token", token);
        bodys.put("cityId", cityId);
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtil.doPost(host, path, method, headers, querys, bodys);
//            return response.toString();
            //获取response的body
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
